const Koa = require('koa') // koa是基于node的框架 与express类似 是小型框架
const Router = require('koa-router') //koa生态体系中的路由中间件
const server = require('koa-static') //静态服务器中间件
const koaBody = require('koa-body')
const tinify = require('tinify')
const path = require('path')
const fs = require('fs')
let router = new Router()
let app = new Koa()

tinify.key = 'WmG89ZPmyvvWFmtNW9L3CC6JcTpP7tTL'

const home = server(path.join(__dirname + '/public/'))
app.use(home)

app.use(koaBody({
  multipart: true, //携带附件
  formidable: {
    maxFieldsSize: 2000 * 1024 * 1024 // 限制大小200kb
  }
}))
// 表单页面
// MVC + router
let new1;
router.post('/uploadPic', async (ctx) => {
  const file = ctx.request.files.file
  // console.log(file);
  const reader = fs.createReadStream(file.path)
  const myDate = new Date()
  const newFileName = myDate.getTime() + '.' + file.name.split('.')[1]
  // console.log(newFileName);
  const targetPath = path.join(__dirname, './public/image/') + newFileName
  // console.log(targetPath);
  new1 = targetPath
  const upStream = fs.createWriteStream(targetPath);
  reader.pipe(upStream);
  ctx.body = '上传成功'
})

router.get('/zipimg', async (ctx) => {
  // req + res 就是这一次用户访问Web的上下文环境
  let sourse = tinify.fromFile(new1)
  sourse.toFile(new1)
  ctx.body = '压缩成功'
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(3300, () => {
  console.log('3300端口已启动');
})